//
//  CreateGroupVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/20.
//

import UIKit

class CreateGroupVC: BaseVC {

    @IBOutlet weak var doneBtn: UIButton!
    @IBOutlet weak var coll: UICollectionView!
    var data = [DMCCUser]()
    var blockStr: ((String) -> ())?
    var selectArray = [DMCCUser]()
//    var indexArray : Array<Any> = []
    // 排序后分组数据
    private var objectsArray : [[Any]]?
    // 头部标题keys
    private var keysArray:[String]? = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = kGrayBG
        self.setup()
        // Do any additional setup after loading the view.
        coll.showsVerticalScrollIndicator = false
        coll.showsHorizontalScrollIndicator = false
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 0
        coll.dataSource = self
        coll.delegate = self
        flowLayout.scrollDirection = .horizontal
        coll.collectionViewLayout = flowLayout
        coll.register(UINib(nibName: "CreateGroupCell", bundle: nil), forCellWithReuseIdentifier: "CreateGroupCell")
        
        self.requestData(isRefresh: false)
    }
    
    func setData(data: [DMCCUser]) {
        self.data = data
        if self.data.count > 0 {
            let str = KLocalizedString("完成") + "(" + "\(data.count)" + ")"
            doneBtn.tintColor = UIColor.MainColor
            doneBtn.setTitle(str, for: .normal)
        }else {
            doneBtn.tintColor = UIColor.gray
            doneBtn.setTitle("完成", for: .normal)
        }
        
//        let str = String(format: "%(@)(%ld)", KLocalizedString("完成"), data.count)
        coll.reloadData()
    }
    
    func requestData (isRefresh:Bool) {
        dataSource.removeAll()
        let friendArr = gosnFriend.getFriendList()
        for f in friendArr {
            self.getUser(friendID: f.friendId, count: friendArr.count)
        }
    }
    
    func getUser (friendID:String,count:Int) {
        let user = gosnUser.getUserInfoDefault(friendID)
        dataSource.append(user)
        if dataSource.count == count {
            self.sort()
        }
    }
    
    func sort () {
        DispatchQueue.global().async {
//            allDataArray =
            UILocalizedIndexedCollation.getCurrentKeysAndObjectsData(needSortArray: self.dataSource as NSArray) { (dataArray,titleArray) in
                self.objectsArray = dataArray
                self.keysArray    = titleArray
                GK_main_async_safe {
                    self.tableView.reloadData()
                }
            }
        }
    }

    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return keysArray!.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let array = objectsArray![section] as Array<Any>
        return array.count
    }
    
    //MARK: 这是Setion标题 以及右侧索引数组设置
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section != 0 {
            return keysArray?[section]
        }
        return ""
    }
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keysArray
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        tableView.scrollToRow(at: NSIndexPath(row: 0, section: index) as IndexPath, at: .top, animated: true)
        return index
    }
    
    //MARK: 设置表头的高度。如果使用自定义表头，该方法必须要实现，否则自定义表头无法执行，也不会报错
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section != 0 {
            return 10.0
        }
        return 15
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
        let array = objectsArray![indexPath.section]
        let user = array[indexPath.row] as! DMCCUser
        cell.setUserInfo(userInfo: user)
        cell.selectImg.isHidden = false
        if user.uiData as? String == "1" {
            cell.selectImg.image = UIImage(named: "select_s")
        }else{
            cell.selectImg.image = UIImage(named: "select_n")
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        let array = objectsArray![indexPath.section]
        let user = array[indexPath.row] as! DMCCUser
        user.uiData = user.uiData as? String == "1" ? "" : "1"
        self.tableView.reloadData()
        
        updateCollView()
    }
    
    func updateCollView () {
        selectArray.removeAll()
        let allArray = objectsArray!
        for array in allArray {
            for user in array {
                let info = user as! DMCCUser
                if info.uiData as? String == "1" {
                    self.selectArray.append(info)
                }
            }
        }
        self.setData(data: self.selectArray)
    }
    
    // MARK: - UICollectionViewDataSource
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CreateGroupCell", for: indexPath) as! CreateGroupCell
        let info = data[indexPath.row]
        cell.img.sd_setImage(with: URL(string: info.portrait), placeholderImage: SDImageDefault)
        return cell
    }
    
    // MARK: - UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 30, height: 30)
    }
    
    func setup () {

        tableStytle = .grouped
        tableView.frame = CGRect(x: 0, y: GKNavHeight + 55, width: kScreenWidth, height: kScreenHeight - GKNavHeight - 55)
//        tableView.separatorInset = UIEdgeInsets(top: 0, left: 76, bottom: 0, right: 0)
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
    }

    @IBAction func back(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func done(_ sender: Any) {
        if self.selectArray.count == 0 {
            dismiss(animated: true)
        }else{
            self.createGroup()
        }
    }

    func createGroup () {
        
        GK_main_async_safe {
            MHAlert.showMessage(KLocalizedString("AlertLoading"))
        }
        var members = [String]()
        for user in self.selectArray {
            members.append(user.userId)
        }
        
        var memberIds = Array(members)
        let userId = gosnUser.myId()
        if !memberIds.contains(userId) {
            memberIds.insert(userId, at: 0)
        }

//        var name: String?
        let firstUserId = memberIds.first!
        let userInfo = gosnUser.getUserInfoDefault(firstUserId)
       var name : String = userInfo.getAlias()
        for i in 1..<min(8, memberIds.count) {
            let user = gosnUser.getUserInfoDefault(memberIds[i])
            let userName : String = user.getDisplayName()
            
            if name.count + userName.count + 1 > 16 {
                    name = "\(name)\(KLocalizedString("de"))\(KLocalizedString("group"))"
                    break
                }
            name = "\(name),\(userName)"
            
        }
        
        if !name.hasSuffix(KLocalizedString("group")) {
            name = name + KLocalizedString("GroupChat")
        }
//        name = name + KLocalizedString("GroupChat")

        let portraitImage = createHeadImg(memberIds: memberIds)!
        let portraitData = portraitImage.jpegData(compressionQuality: 1)
//        let fileSvcTool = FileTool()
        
        Task {
            let (portraitUrl,_) = await ghttpService.uploadGroupPortrait(portraitData!)
            
            let (groupId, err) = await gosnGroup.createGroup(name, portraitUrl!, memberIds)
            await MainActor.run {
                if let err = err {
                    MHAlert.showMessage("\(err.description)")
                }else{
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
                    self.blockStr!(groupId!)
                    
                    GK_main_async_safe {
                        MHAlert.showMessage(KLocalizedString("GreatGroupSuccess"))
                    }
                    
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
                        self.dismiss(animated: true, completion: nil)
                    }))

                }
            }

        }
//        let portraitUrl = fileSvcTool.uploadPortrait(mediaData: portraitData!) { link in
//            // 成功回调
//            
//        } progress: { uploaded, total in
//            // 进度回调
//        } error: { errorCode in
//            // 错误回调
//            GK_main_async_safe {
//                MHAlert.showMessage("上传头像失败")
//            }
//        }
        
        
        
//        APIManager.shared.createGroup(member: memberIds, portrait: portraitUrl!, name: name) { data in
//            
//            let responseDict = data
//            let content = responseDict["groupInfo"] as! [String: Any]
//            let dic = NSMutableDictionary(dictionary: content)
//            let group = DMCCIMService.getInstance().updateGroupInfo(dic)
//            
//            let g2 = DMCCIMService.getInstance().getGroupInfo(group?.groupId, refresh: false)
//            
//            DMCCIMService.getInstance().saveGroup(group?.groupId, status: true) { isSuccess, json, error in
//                if isSuccess {
//                    
//                } else {
//                    GK_main_async_safe {
//                        MHAlert.showMessage(KLocalizedString("GreatGroupError"))
//                    }
//                }
//            }
//
//            DMCCIMService.getInstance().updateGroupFav(group, fav: true)
//
//            let conversation = gosnConversation.getConversationInfo(group?.groupId)
//            if conversation == nil {
//                DMCCIMService.getInstance().insertConversation(with: group)
//            }
//                
//            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
//            if let groupId = group?.groupId {
//                self.blockStr!(groupId)
//            }
//            
//            GK_main_async_safe {
//                MHAlert.showMessage(KLocalizedString("GreatGroupSuccess"))
//            }
//            
//            DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
//                self.dismiss(animated: true, completion: nil)
//            }))
//
//            
//        } error: { err in
//            GK_main_async_safe {
//                MHAlert.showMessage(err)
//            }
//        }

    }

    func createHeadImg(memberIds: [String]) -> UIImage? {
        let portraitWidth: CGFloat = 120
        let combineHeadView = UIView(frame: CGRect(x: 0, y: 0, width: portraitWidth, height: portraitWidth)) 
        combineHeadView.backgroundColor = UIColor.init(hex: 0xf9f9f9)
        
        var users: [DMCCUser] = []
        let userId = gosnUser.myId()
        if !memberIds.contains(userId) {
            let user = gosnUser.getUserInfoDefault(userId)
            users.append(user)
        }

        for userId in memberIds {
            let user = gosnUser.getUserInfoDefault(userId) as DMCCUser
            users.append(user)
            if users.count >= 9 {
                break
            }
        }
        
        let padding: CGFloat = 5
        let numPerRow = users.count <= 4 ? 2 : 3
        let row = (users.count - 1) / numPerRow + 1
        let column = numPerRow
        let firstCol = users.count - (row - 1) * column
        let width = (portraitWidth - padding) / CGFloat(numPerRow) - padding
        let y = (portraitWidth - (CGFloat(row) * (width + padding) + padding)) / 2
        
        for i in 0..<row {
            let c = i == 0 ? firstCol : column
            let x = (portraitWidth - (CGFloat(c) * (width + padding) + padding)) / 2
            
            for j in 0..<c {
                let imageView = UIImageView(frame: CGRect(x: x + CGFloat(j) * (width + padding) + padding, y: y + CGFloat(i) * (width + padding) + padding, width: width, height: width))
                let index = i == 0 ? j : j + (i - 1) * column + firstCol
                let user = users[index]
                imageView.sd_setImage(with: URL(string: user.portrait), placeholderImage: SDImageDefault)
                combineHeadView.addSubview(imageView)
            }
        }
        
        UIGraphicsBeginImageContextWithOptions(combineHeadView.frame.size, false, 2.0)
        combineHeadView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}
